<template>
    <Layout style="height: 100%" class="main">
        <Header :class="['header-con', winExtend ? 'hide' : 'show']">
            <header-bar
                :collapsed="collapsed"
                @on-coll-change="handleCollapsedChange"
            >
                <!-- 需要放在菜单上面的内容，如Logo，写在side-menu标签内部，如下 -->
                <div slot="logo" class="logo-con" :style="{ width: logoConWidth }">
                    <img :src="logoSrc" @click="goHome" />
                </div>
                <user :user-avator="userAvator" />
                <!-- 常用菜单 （以组件的方式）-->
                <!-- 消息 （以组件的方式）-->
                <fullscreen
                    v-model="isFullscreen"
                    style="margin-right: 10px;color: #fff;"
                />
                <span
                    style="margin-right: 10px;color: #fff; position:relative"
                    @click="msgVisible = true"
                >消息
                    <span class="red-notice" v-if="noticeNum != 0">
                        {{ noticeNum}}
                    </span>
                </span>
            </header-bar>
        </Header>
        <Layout class="main-content-con">
            <Sider
                v-show="showTags"
                hide-trigger
                collapsible
                :width="180"
                :collapsed-width="64"
                v-model="collapsed"
                :class="['left-sider', winExtend ? 'hide' : 'show']"
                :style="{ overflow: 'hidden' }"
            >
                <side-menu
                    v-if="showTags"
                    :hideMenu="!showTags"
                    :homePageName="homePageName"
                    :accordion="false"
                    ref="sideMenu"
                    :active-name="$route.name"
                    :collapsed="collapsed"
                    @on-select="turnToPage"
                    :menu-list="menuList"
                >
                </side-menu>
            </Sider>
            <Content>
                <Layout class="main-layout-con">
                    <div v-if="showTags" :class="['tag-nav-wrapper', winExtend ? 'hide' : 'show']">
                        <tags-nav
                            :value="$route"
                            :homePageName="homePageName"
                            @input="handleClick"
                            :list="tagNavList"
                            @on-close="handleCloseTag"
                        />
                    </div>
                    <Content class="content-wrapper">
                        <KeepAliveContent />
                        <div
                            class="change-window-size"
                            @click="setWinSize"
                            v-show="showWinExtend"
                        >
                            <span>{{ winExtend ? "退出全屏" : "全屏查看" }}</span>
                            <Icon
                                :size="16"
                                :type="winExtend ? 'ios-contract' : 'ios-expand'"
                            />
                        </div>
                    </Content>
                </Layout>
            </Content>
        </Layout>
        <MessageSide v-model="msgVisible" />
    </Layout>
</template>
<script>
import SideMenu from './components/side-menu'
import HeaderBar from './components/header-bar'
import TagsNav from './components/tags-nav'
import User from './components/user'
import Fullscreen from './components/fullscreen'
import KeepAliveContent from './components/keep-alive-content'
import MessageSide from './components/message/message-side'
import { mapMutations } from 'vuex'
import { getNextRoute, routeEqual, getToken, getHomeRouteByRole } from '@/libs/util'
import minLogo from '@/assets/images/logo-min.png'
import maxLogo from '@/assets/images/logo.png'

import config from '@/config'
import { getPermission, resolveTypeByPath } from '@/libs/permission'

export default {
    name: 'Main',
    components: {
        SideMenu,
        HeaderBar,
        TagsNav,
        Fullscreen,
        User,
        KeepAliveContent,
        MessageSide
    },
    data () {
        return {
            pathType: resolveTypeByPath(this.$route.path),
            noticeNum: 0,
            msgVisible: false,
            collapsed: false,
            isFullscreen: false,
            winExtend: false, // 窗口是否扩展
            showWinExtend: false // 是否显示窗口扩展按钮
        }
    },
    computed: {
        menuList () {
            const role = this.$store.state.user.roleType
            return Number(role) === 4 ? getPermission(role, this.pathType) : getPermission(role)
        },
        homePageName () {
            return this.$store.state.app.homeRoute.name
        },
        logoConWidth () {
            return this.collapsed ? '64px' : '224px'
        },
        logoSrc () {
            return this.collapsed ? minLogo : maxLogo
        },
        tagNavList () {
            return this.$store.state.app.tagNavList
        },
        userAvator () {
            return this.$store.state.user.avatorImgPath
        },
        showTags () {
            const { hideTags = false } = this.$route.meta
            return !hideTags
        }
    },
    methods: {
        ...mapMutations(['setTagNavList', 'addTag', 'setHomeRoute']),
        goHome () {
            console.log(this.$store.state.user.roleType)
            let roleType = this.$store.state.user.roleType
            if (roleType == 4) {
                this.$router.push({
                    path: '/student'
                })
            }
        },
        turnToPage (route) {
            let { name, params, query } = {}
            if (typeof route === 'string') {
                name = route
            } else {
                name = route.name
                params = route.params
                query = route.query
            }
            if (name.indexOf('isTurnByHref_') > -1) {
                window.open(name.split('_')[1])
                return
            }
            this.$router.push({
                name,
                params,
                query
            })
        },

        handleCollapsedChange (state) {
            this.collapsed = state
        },

        handleCloseTag (res, type, route) {
            this.removeTags(res, type, route)
        },

        removeTags (res, type, route) {
            let openName = this.homePageName
            if (type === 'all') {
                this.turnToPage(openName)
            } else if (routeEqual(this.$route, route)) {
                if (type === 'others') {
                    openName = route.name
                } else {
                    const nextRoute = getNextRoute(this.tagNavList, route)
                    this.$router.push(nextRoute)
                    openName = nextRoute.name
                }
            }
            this.setTagNavList(res)
            this.$refs.sideMenu.updateOpenName(openName)
        },

        handleClick (item) {
            this.turnToPage(item)
        },

        setWinSize () {
            this.winExtend = !this.winExtend
        },
        // webstock 连接
        connectWebStock () {
            if (window.WebSocket) {
                const url = config.webStockUrl
                const token = getToken()
                const ws = new window.WebSocket(url + '/notify/' + token)
                ws.onopen = function () {
                    console.log(`websocket 已连接`)
                }
                ws.onclose = function () {
                    console.log(`websocket 连接已关闭`)
                }
                ws.onmessage = evt => {
                    try {
                        let received_msg = JSON.parse(evt.data)
                        this.noticeNum = received_msg.notifyNum || 0
                    } catch (error) {
                        console.log(error)
                    }
                }
                ws.onerror = function (err) {
                    console.log(err)
                }
            } else {
                this.$Notice.warning('您的浏览器不支持 WebSocket!')
            }
        }
    }, // methods end
    mounted () {
        this.connectWebStock()
    },
    watch: {
        $route (newRoute, route) {
            this.showWinExtend = (newRoute.meta && newRoute.meta.fullScreen) || false
            if (!this.showWinExtend && this.winExtend) this.winExtend = false
            // hideTags更改清空 tagNavList 重新设置首页
            const newHide = newRoute.meta.hideTags
            const oldHide = route.meta.hideTags
            this.pathType = resolveTypeByPath(this.$route.path)
            if (newHide !== oldHide) {
                // 重新设置首页 清空标签
                this.setHomeRoute(getHomeRouteByRole(this.menuList, this.$router.options.routes))
                this.setTagNavList([])
            }
        }
    }
}
</script>

<style lang="less">
@import url("./main.less");
.red-notice {
  height: 13px;
  width: 13px;
  color: #fff;
  font-size: 12px;
  position: absolute;
  right: -8px;
  top: 18px;
  background: red;
  border-radius: 6px;
  text-align: center;
  line-height: 12px;
}
.content-wrapper {
  position: relative;
  .change-window-size {
    color: #767884;
    position: absolute;
    top: 0;
    right: 2px;
    height: 18px;
    line-height: 14px;
    cursor: pointer;
    box-sizing: border-box;
    &:hover,
    &:active {
      color: #1177e8;
    }
    span {
      margin-right: 2px;
      line-height: 16px;
      vertical-align: middle;
    }
  }
}
</style>
